package user

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/jinzhu/copier"
	"hzjt-oam/admin-api/internal/config"
	"hzjt-oam/admin-api/internal/svc"
	"hzjt-oam/admin-api/internal/types"
	"hzjt-oam/admin-api/model/user"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ReSetPasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewReSetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReSetPasswordLogic {
	return &ReSetPasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReSetPasswordLogic) ReSetPassword(req *types.ReSetPasswordReq) (resp *types.ReSetPasswordResp, err error) {
	if len(strings.TrimSpace(req.Password)) == 0 {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("密码不能为空,请求信息失败,参数:%s", reqStr)
		return nil, errors.New("用户名或密码不能为空")
	}

	one, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.New("获取用户失败")
	}
	resp_model := &user.SysUser{}
	copier.Copy(resp_model, one)
	resp_model.Password = config.Md5(req.Password)

	userId, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, errors.New("验证token未通过")
	}
	user_two, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
	resp_model.LastUpdateBy = user_two.Name
	resp_model.CreateBy = user_two.Name
	resp_model.LastUpdateTime = time.Now().Unix()

	err = l.svcCtx.UserModel.Update(l.ctx, resp_model)
	if err != nil {
		err = errors.New("密码重置失败")
		return nil, err
	}
	return &types.ReSetPasswordResp{"成功"}, nil
}
